<script setup lang="ts">
import { getCurrentInstance, nextTick, onMounted, onUnmounted, reactive, ref, useTemplateRef, watch } from 'vue';
import { useBoolean } from '@sa/hooks';
import { fetchCheckCaptcha, fetchGetCaptcha } from '@/service/api/auth';
import { resetSizeOptions } from '../utils/util';
import { aseEncrypt } from '../utils/ase';
import type { ImageStyle, Instance } from '../utils/util';

defineOptions({ name: 'VerifySlide' });

interface Props {
  mode?: string;
  captchaType: string;
  type?: string;
  vSpace?: number;
  explain?: string;
  imgSize?: ImageStyle;
  barSize?: ImageStyle;
}

interface Emit {
  (event: 'setClickShow', bool: boolean): void;
  (event: 'ready'): void;
  (event: 'success', data: CommonType.RecordObject): void;
  (event: 'error'): void;
  (event: 'closeBox'): void;
}

interface SetSize {
  imgHeight: string;
  imgWidth: string;
  barHeight: string;
  barWidth: string;
}

const props = withDefaults(defineProps<Props>(), {
  mode: 'fixed',
  type: '1',
  vSpace: 5,
  explain: '向右滑动完成验证',
  imgSize: () => ({
    width: '310px',
    height: '155px'
  }),
  blockSize: () => ({
    width: '50px',
    height: '50px'
  }),
  barSize: () => ({
    width: '40px',
    height: '40px'
  }),
  defaultImg: ''
});

const emit = defineEmits<Emit>();

const instance = getCurrentInstance();

/** 后端返回的加密秘钥字段 */
const secretKey = ref('');
/** 是否通过的标识 */
const { bool: passFlag, setBool: setPassFlag } = useBoolean();
/** 验证码背景图片 */
const backImgBase = ref('');
/** 验证滑块的背景图片 */
const blockBackImgBase = ref('');
/** 后端返回的唯一token值 */
const backToken = ref('');
/** 移动开始的时间 */
const startMoveTime = ref(0);
/** 移动结束的时间 */
const endMovetime = ref(0);

const tipWords = ref('');
const text = ref('');
const finishText = ref('');

const setSize = reactive<SetSize>({
  imgHeight: '0px',
  imgWidth: '0px',
  barHeight: '0px',
  barWidth: '0px'
});

const moveBlockLeft = ref();
const leftBarWidth = ref();
const leftBarBg = ref('#ecf8ff');

/** 移动中样式 */
const moveBlockBackgroundColor = ref();
const leftBarBorderColor = ref('#ddd');
const iconColor = ref();
const iconClass = ref('material-symbols-arrow-forward-ios');

/** 鼠标状态 */
const { bool: status, setBool: setStatus } = useBoolean();

/** 是否验证完成 */
const { bool: isEnd, setBool: setIsEnd } = useBoolean();
const { bool: showRefresh, setBool: setShowRefresh } = useBoolean(true);
const { bool: rotating, setBool: setRotating } = useBoolean();
const transitionLeft = ref('');
const transitionWidth = ref('');

/** 滑块图片是否显示，图片加载失败就不显示 */
const { bool: blockImgVisible, setBool: setBlockImgVisible } = useBoolean(true);

const startLeft = ref();

const barArea = useTemplateRef('verifyBarArea');
const verifyMoveBlock = useTemplateRef('verifyMoveBlock');

watch(
  () => props.type,
  () => {
    init();
  },
  { immediate: true }
);

onMounted(() => {
  const el = instance?.proxy?.$el;
  el.onselectstart = () => false;
});

onUnmounted(() => {
  window.removeEventListener('touchmove', move);
  window.removeEventListener('mousemove', move);
  window.removeEventListener('touchend', end);
  window.removeEventListener('mouseup', end);
});

/** 加载页面 */
async function init() {
  text.value = props.explain;
  getPictrue();
  await nextTick();
  /** 重新设置宽度高度 */
  const setSizeOptions = resetSizeOptions(instance?.proxy as Instance, props.imgSize, props.barSize);
  Object.assign(setSize, setSizeOptions);
  emit('ready');

  // 鼠标滑动
  window.removeEventListener('touchmove', move);
  window.removeEventListener('mousemove', move);

  window.addEventListener('touchmove', move, { passive: true });
  window.addEventListener('mousemove', move, { passive: true });

  // 鼠标松开
  window.removeEventListener('touchend', end);
  window.removeEventListener('mouseup', end);

  window.addEventListener('touchend', end, { passive: true });
  window.addEventListener('mouseup', end, { passive: true });
}

/** 鼠标按下 */
function start(e: MouseEvent | TouchEvent) {
  let x = 0;
  if (e instanceof TouchEvent) {
    /** 兼容移动端 */
    x = e.touches[0].pageX;
  } else if (e instanceof MouseEvent) {
    /** 兼容PC端 */
    x = e.clientX;
  }
  startLeft.value = Math.floor(x - barArea.value!.getBoundingClientRect().left);
  /** 开始滑动的时间 */
  startMoveTime.value = Number(new Date());
  if (!isEnd.value) {
    text.value = '';
    moveBlockBackgroundColor.value = '#1e80ff';
    leftBarBorderColor.value = '#1e80ff';
    iconColor.value = '#fff';
    e.stopPropagation();
    setStatus(true);
  }
}
// 鼠标移动
function move(e: MouseEvent | TouchEvent) {
  if (status.value && !isEnd.value) {
    let x = 0;
    if (e instanceof TouchEvent) {
      /** 兼容移动端 */
      x = e.touches[0].pageX;
    } else if (e instanceof MouseEvent) {
      /** 兼容PC端 */
      x = e.clientX;
    }
    const bar_area_left = barArea.value!.getBoundingClientRect().left;
    /** 拖动后小方块的left值 */
    const moveWidth = x - bar_area_left - startLeft.value;
    const maxMoveWidth = barArea.value!.getBoundingClientRect().width - Number.parseInt(props.barSize.width, 10);
    if (moveWidth <= maxMoveWidth && moveWidth >= 0) {
      moveBlockLeft.value = `${x - bar_area_left - startLeft.value}px`;
      leftBarWidth.value = `${x - bar_area_left - startLeft.value}px`;
      verifyMoveBlock.value!.style.width = `${Number.parseInt(props.barSize.width, 10) + 2}px`;
      verifyMoveBlock.value!.style.height = `${Number.parseInt(props.barSize.width, 10) + 2}px`;
      verifyMoveBlock.value!.style.top = '-1px';
    }
  }
}

/** 鼠标松开 */
async function end() {
  endMovetime.value = Number(new Date());
  /** 判断是否重合 */
  if (status.value && !isEnd.value) {
    let moveLeftDistance = Number.parseInt((moveBlockLeft.value || '').replace('px', ''), 10);
    moveLeftDistance = (moveLeftDistance * 310) / Number.parseInt(setSize.imgWidth, 10);
    const params: LoginApi.CheckCaptchaParams = {
      captchaType: props.captchaType,
      pointJson: secretKey.value
        ? aseEncrypt(JSON.stringify({ x: moveLeftDistance, y: 5.0 }), secretKey.value)
        : JSON.stringify({ x: moveLeftDistance, y: 5.0 }),
      token: backToken.value
    };
    const errorFn = () => {
      leftBarBg.value = '#fef0f0';
      moveBlockBackgroundColor.value = 'rgb(245, 34, 45)';
      leftBarBorderColor.value = 'rgb(245, 34, 45)';
      iconColor.value = '#fff';
      iconClass.value = 'material-symbols-close-rounded';
      setPassFlag(false);
      setTimeout(() => {
        refresh();
      }, 1000);
      emit('error');
      tipWords.value = '验证失败';
      setTimeout(() => {
        tipWords.value = '';
      }, 1000);
    };
    const { data } = await fetchCheckCaptcha(params);
    try {
      if (data) {
        leftBarBg.value = 'rgba(24, 160, 88, 0.22)';
        moveBlockBackgroundColor.value = '#18a058';
        leftBarBorderColor.value = '#18a058';
        iconColor.value = '#fff';
        iconClass.value = 'material-symbols-check';
        setShowRefresh(false);
        setIsEnd(true);
        if (props.mode === 'pop') {
          setTimeout(() => {
            emit('setClickShow', false);
            setTimeout(() => {
              refresh();
            }, 500);
          }, 1500);
        }
        setPassFlag(true);
        tipWords.value = `${((endMovetime.value - startMoveTime.value) / 1000).toFixed(2)}s 验证成功`;
        const captchaVerification = secretKey.value
          ? aseEncrypt(`${backToken.value}---${JSON.stringify({ x: moveLeftDistance, y: 5.0 })}`, secretKey.value)
          : `${backToken.value}---${JSON.stringify({ x: moveLeftDistance, y: 5.0 })}`;
        /** 延迟操作，直接使用 setTimeout 不知道为什么会有警告 */
        await new Promise(resolve => {
          setTimeout(() => {
            resolve(true);
          }, 1000);
        });
        tipWords.value = '';
        emit('closeBox');
        emit('success', { code: captchaVerification });
      } else {
        errorFn();
      }
    } catch {
      errorFn();
    }
    status.value = false;
  }
}

function refresh() {
  setShowRefresh(true);
  finishText.value = '';

  transitionLeft.value = 'left .3s';
  moveBlockLeft.value = 0;

  leftBarWidth.value = undefined;
  transitionWidth.value = 'width .3s';

  leftBarBorderColor.value = '#ddd';
  moveBlockBackgroundColor.value = '#fff';
  leftBarBg.value = '#ecf8ff';
  iconColor.value = '#000';
  iconClass.value = 'material-symbols-arrow-forward-ios';
  setIsEnd(false);

  /** 滑块重置 */
  if (verifyMoveBlock.value! !== null) {
    verifyMoveBlock.value!.style.width = `${Number.parseInt(props.barSize.width, 10)}px`;
    verifyMoveBlock.value!.style.height = `${Number.parseInt(props.barSize.width, 10)}px`;
    verifyMoveBlock.value!.style.top = '0px';
  }

  getPictrue();
  setTimeout(() => {
    transitionWidth.value = '';
    transitionLeft.value = '';
    text.value = props.explain;
  }, 300);
}

/** 请求背景图片和验证图片 */
async function getPictrue() {
  const params: LoginApi.GetCaptchaParams = {
    captchaType: props.captchaType,
    clientUid: localStorage.getItem('slider') || '',
    ts: Date.now()
  };
  try {
    setRotating(true);
    const { data } = await fetchGetCaptcha(params);
    if (data) {
      backImgBase.value = data.originalImageBase64;
      blockBackImgBase.value = data.jigsawImageBase64;
      backToken.value = data.token;
      secretKey.value = data.secretKey;
    }
  } catch {
    // text.tipWords = data.repMsg;
  } finally {
    // 判断接口请求次数是否失效
    // if (res.code === '6201') {
    //   backImgBase.value = '';
    //   blockBackImgBase.value = '';
    // }
    setRotating(false);
  }
}
</script>

<template>
  <div class="relative">
    <div
      v-if="type === '2'"
      class="verify-img-out"
      :style="{ height: Number.parseInt(setSize.imgHeight, 10) + vSpace + 'px' }"
    >
      <div class="verify-img-panel" :style="{ width: setSize.imgWidth, height: setSize.imgHeight }">
        <img v-if="backImgBase" :src="'data:image/png;base64,' + backImgBase" class="block size-full" />
        <div v-else class="defaultImg"></div>
        <div v-show="showRefresh" class="verify-refresh" @click="refresh">
          <SvgIcon local-icon="ic-round-refresh" class="iconfont icon-refresh" :class="{ rotating }"></SvgIcon>
        </div>
        <Transition name="tips">
          <span v-if="tipWords" class="verify-tips" :class="passFlag ? 'suc-bg' : 'err-bg'">{{ tipWords }}</span>
        </Transition>
      </div>
    </div>
    <!-- 公共部分 -->
    <div
      ref="verifyBarArea"
      class="verify-bar-area"
      :style="{ width: setSize.imgWidth, height: barSize.height, 'line-height': barSize.height }"
    >
      <span class="verify-msg">{{ text }}</span>
      <div
        class="verify-left-bar"
        :style="{
          width: leftBarWidth !== undefined ? leftBarWidth : barSize.width,
          height: barSize.height,
          'border-color': leftBarBorderColor,
          transition: transitionWidth,
          background: leftBarBg
        }"
      >
        <span class="verify-msg">{{ finishText }}</span>
        <div
          ref="verifyMoveBlock"
          class="verify-move-block"
          :style="{
            width: barSize.width,
            height: barSize.height,
            'background-color': moveBlockBackgroundColor,
            left: moveBlockLeft,
            transition: transitionLeft
          }"
          @touchstart.passive="start"
          @mousedown.passive="start"
        >
          <!-- <i class="iconfont verify-icon" :class="[iconClass]" :style="{ color: iconColor }" /> -->
          <SvgIcon class="iconfont verify-icon mx-auto" :local-icon="iconClass" :style="{ color: iconColor }"></SvgIcon>
          <div
            v-if="type === '2'"
            class="verify-sub-block"
            :style="{
              width: Math.floor((Number.parseInt(setSize.imgWidth, 10) * 47) / 310) + 'px',
              height: setSize.imgHeight,
              top: '-' + (Number.parseInt(setSize.imgHeight, 10) + vSpace) + 'px',
              'background-size': setSize.imgWidth + ' ' + setSize.imgHeight
            }"
          >
            <img
              v-show="blockImgVisible"
              :src="'data:image/png;base64,' + blockBackImgBase"
              class="block size-full"
              @load="setBlockImgVisible(true)"
              @error="setBlockImgVisible(false)"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped></style>
